package org.linlinjava.litemall.db.service;

import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.linlinjava.litemall.db.dao.*;
import org.linlinjava.litemall.db.domain.*;
import org.linlinjava.litemall.db.vo.AdminIncomeVo;
import org.linlinjava.litemall.db.vo.IncomeOrderVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class LitemallIncomeService {
    @Resource
    private IncomeMapper incomeMapper;
    @Resource
    private LitemallIncomeMapper  litemallIncomeMapper;
    @Resource
    private UserStatisticsMapper userStatisticsMapper;
    @Resource
    private LitemallUserMapper litemallUserMapper;
    @Resource
    private LitemallUserBalanceLogMapper userBalanceLogMapper;
    @Resource
    private LitemallOrderMapper litemallOrderMapper;
    @Resource
    private LitemallOrderGoodsMapper orderGoodsMapper;
    @Resource
    private LitemallGoodsMapper goodsMapper;
    @Resource
    private LitemallDistributionMapper distributionMapper;
    @Resource
    private LitemallSystemConfigService systemConfigService;
    @Resource
    private LitemallUserLevelMapper userLevelMapper;

    public List<IncomeOrderVo> queryList(Integer userId, Integer showType, Integer page, Integer limit) {
        PageHelper.startPage(page, limit);
        return incomeMapper.findIncomeOrder(userId,showType);
    }

    public List<AdminIncomeVo> queryAdminList(Integer id, Integer userId, Integer incomeUserId, Integer disType, Integer disLevel,Integer status, Byte orderSn,  Integer page, Integer limit, String sort, String order) {
        PageHelper.startPage(page, limit);
        return incomeMapper.queryAdminList(id,userId,incomeUserId,disType,disLevel,status,orderSn,page,limit,sort,order);
    }

    @Transactional
    public int updateAccount(String userName, AdminIncomeVo user) {

        LitemallIncomeExample example = new LitemallIncomeExample();
        example.or().andOrderSnEqualTo(user.getOrder_sn()).andDeletedEqualTo(false);
        List<LitemallIncome> incomes = litemallIncomeMapper.selectByExample(example);

        List<LitemallIncome> newInocomes = incomes.stream().filter(e->e.getStatus() == 0).collect(Collectors.toList());
        //订单异常
        if(newInocomes.size() != incomes.size()){
            return -1;
        }

        for (LitemallIncome income : incomes){
            //更新入账状态
            LitemallIncome tmp = new LitemallIncome();
            tmp.setId(income.getId());
            tmp.setUpdateTime(LocalDateTime.now());
            tmp.setStatus(1);
            litemallIncomeMapper.updateByPrimaryKey(tmp);

            //查询最近余额
            LitemallUser litemallUser = litemallUserMapper.selectByPrimaryKey(income.getUserId());

            //修改用户余额
            userStatisticsMapper.updateBalance(income.getUserId(), income.getPrice());

            //查询最近余额
            LitemallUser newLitemallUser = litemallUserMapper.selectByPrimaryKey(income.getUserId());

            //记录日志
            LitemallUserBalanceLog log = new LitemallUserBalanceLog();
            log.setAddTime(LocalDateTime.now());
            log.setDeleted(false);
            log.setUserId(newLitemallUser.getId());
            log.setType(3);//提现
            log.setBeforeBalance(litemallUser.getBalance());
            log.setAfterBalance(newLitemallUser.getBalance());
            log.setUsername(userName);
            userBalanceLogMapper.insert(log);
        }
        return 0;
    }

    /**
     * 支付成功，分佣
     * @param orderSn
     */
    public void paySuccess(String orderSn) {
        LitemallOrderExample example = new LitemallOrderExample();
        example.or().andOrderSnEqualTo(orderSn).andDeletedEqualTo(false);
        LitemallOrder order = litemallOrderMapper.selectOneByExample(example);
        Integer userId = order.getUserId();

        //获取商品
        LitemallOrderGoodsExample goodsExample = new LitemallOrderGoodsExample();
        goodsExample.or().andOrderIdEqualTo(order.getId()).andDeletedEqualTo(false);
        List<LitemallOrderGoods> goodsList = orderGoodsMapper.selectByExample(goodsExample);
        Integer goodsId = goodsList.get(0).getGoodsId();
        LitemallGoods goods = goodsMapper.selectByPrimaryKey(goodsId);
        Boolean isSpecial = goods.getIsSpecial();

        Map<String, String>  config = systemConfigService.listDistributionSpecialConfig();
        String litemall_specialConfig_switch = config.get("litemall_specialConfig_switch");

        if(isSpecial && !Boolean.valueOf(litemall_specialConfig_switch)){
            log.info("不是特价商品，或者没有开启特价商品分佣 orderSn={}",orderSn);
            return;
        }

        //直接推广人
        LitemallDistributionExample distributionExample1 = new LitemallDistributionExample();
        distributionExample1.or().andUserIdEqualTo(userId).andDeletedEqualTo(false);
        LitemallDistribution distribution1 = distributionMapper.selectOneByExample(distributionExample1);

        if(distribution1 != null){
            BigDecimal direct = null;
            BigDecimal inDirect = null;
            BigDecimal actualPrice = order.getActualPrice();
            int disLevel = 0;
            Integer directUserId = distribution1.getUserId();
            //是否特价商品
            if(isSpecial){
                String litemall_specialConfig_direct = config.get("litemall_specialConfig_direct");
                String litemall_specialConfig_indirect = config.get("litemall_specialConfig_indirect");
                direct = new BigDecimal(litemall_specialConfig_direct);
                inDirect = new BigDecimal(litemall_specialConfig_indirect);
            }else {
                LitemallUser directUser = litemallUserMapper.selectByPrimaryKey(directUserId);
                LitemallUserLevelExample directExample = new LitemallUserLevelExample();
                LitemallUserLevelExample.Criteria criteria = directExample.or();
                criteria.andLevelEqualTo(directUser.getUserLevel()).andLogicalDeleted(false).andStatusEqualTo((byte) 0);
                LitemallUserLevel directUserLevel = userLevelMapper.selectOneByExample(directExample);
                if(directUserLevel != null){
                    direct = directUserLevel.getDirect();
                    inDirect = directUserLevel.getIndirect();
                    disLevel = 1;
                }
            }

            //没有开启
            if(direct == null){
                return;
            }

            //直推分佣
            saveIncome(direct,directUserId,disLevel,orderSn,actualPrice,0);

            //间接接推广人
            LitemallDistributionExample distributionExample2 = new LitemallDistributionExample();
            distributionExample2.or().andUserIdEqualTo(directUserId).andDeletedEqualTo(false);
            LitemallDistribution distribution2 = distributionMapper.selectOneByExample(distributionExample2);
            if(distribution2 != null && inDirect != null){
                Integer inDirectUserId = distribution2.getUserId();
                saveIncome(inDirect,inDirectUserId,disLevel,orderSn,actualPrice,1);
            }

        }
    }

    private void saveIncome(BigDecimal direct, Integer directUserId, int disLevel, String orderSn, BigDecimal actualPrice, Integer disType) {
        LocalDateTime localDateTime = LocalDateTime.now();
        LitemallIncome tmp1 = new LitemallIncome();
        tmp1.setAddTime(localDateTime);
        tmp1.setUpdateTime(localDateTime);
        tmp1.setDeleted(false);
        tmp1.setStatus(0);
        tmp1.setAddTime(localDateTime);
        tmp1.setDisLevel(disLevel);
        tmp1.setDisRate(direct);
        tmp1.setDisType(disType);
        tmp1.setOrderSn(orderSn);
        tmp1.setPrice(actualPrice.multiply(direct));
        tmp1.setUserId(directUserId);
        litemallIncomeMapper.insert(tmp1);
    }
}
